package top.soft.util;

import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.java_websocket.handshake.ServerHandshake;

import top.soft.inter.Observer;
import top.soft.inter.Subject;

/**
 * @author: Amosen
 * @time: 2021-5-1
 */

public class WebSocketClientImpl extends org.java_websocket.client.WebSocketClient implements Subject {

	// 观察者模式，维护一个观察者列表
	private List<Observer> observers = new ArrayList<>();

	public WebSocketClientImpl(URI serverUri) {
		super(serverUri);
		this.waitConnect();
	}

	public void waitConnect() {
		try {
			this.connectBlocking();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	// 开启连接的方法
	@Override
	public void onOpen(ServerHandshake handshakedata) {
		System.out.println("正在进行握手......");
		for (Iterator<String> it = handshakedata.iterateHttpFields(); it.hasNext();) {
			String key = it.next();
			System.out.println(key + ": " + handshakedata.getFieldValue(key));
		}
	}

	@Override
	public void onMessage(String message) {
		// TODO Auto-generated method stub
		System.out.println("接收到消息：" + message);
		// 通知观察者们获取消息
		anounce(message);
	}

	@Override
	public void onClose(int code, String reason, boolean remote) {
		// TODO Auto-generated method stub
		System.out.println("关闭连接......");
	}

	@Override
	public void onError(Exception ex) {
		// TODO Auto-generated method stub
		ex.printStackTrace();
	}

	// 向观察者发送通知
	@Override
	public void anounce(String message) {
		// TODO Auto-generated method stub
		for (Observer observer : observers) {
			observer.acceptAnounce(message);
		}
	}

	@Override
	public void register(Observer observer) {
		// TODO Auto-generated method stub
		this.observers.add(observer);
	}

	@Override
	public void remove(Observer observer) {
		// TODO Auto-generated method stub
		this.observers.remove(observer);
	}

}
